<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>文档解析工具</title>
    <link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.0/font/bootstrap-icons.css">
</head>
<body>
    <div class="container">
        <h1 class="text-center my-4">文档解析工具</h1>
        
        <div class="card mb-4">
            <div class="card-header bg-primary text-white">
                <h5><i class="bi bi-upload"></i> 上传文档</h5>
            </div>
            <div class="card-body">
                <form id="uploadForm" enctype="multipart/form-data">
                    <div class="mb-3">
                        <label for="requirement" class="form-label">需求文档 (PDF)</label>
                        <input class="form-control" type="file" id="requirement" name="requirement" accept=".pdf" required>
                    </div>
                    <div class="mb-3">
                        <label for="test" class="form-label">测试报告 (PDF)</label>
                        <input class="form-control" type="file" id="test" name="test" accept=".pdf" required>
                    </div>
                    <button type="submit" class="btn btn-primary" id="processBtn">
                        <i class="bi bi-gear"></i> 开始解析
                    </button>
                </form>
            </div>
        </div>
        
        <div id="loadingSection" class="text-center py-4" style="display: none;">
            <div class="spinner-border text-primary" role="status">
                <span class="visually-hidden">加载中...</span>
            </div>
            <p class="mt-2">文档处理中，请稍候...</p>
            <p class="text-muted">处理时间可能较长，请耐心等待</p>
        </div>
        
        <div id="resultsSection" style="display: none;">
            <div class="d-flex justify-content-between align-items-center mb-3">
                <h2><i class="bi bi-file-earmark-text"></i> 解析结果</h2>
                <button class="btn btn-success" id="downloadBtn">
                    <i class="bi bi-download"></i> 导出完整报告
                </button>
            </div>
            
            <ul class="nav nav-tabs" id="resultsTab" role="tablist">
                <li class="nav-item" role="presentation">
                    <button class="nav-link active" id="requirements-tab" data-bs-toggle="tab" 
                            data-bs-target="#requirements" type="button" role="tab">
                        <i class="bi bi-list-check"></i> 需求列表
                    </button>
                </li>
                <li class="nav-item" role="presentation">
                    <button class="nav-link" id="tests-tab" data-bs-toggle="tab" 
                            data-bs-target="#tests" type="button" role="tab">
                        <i class="bi bi-clipboard2-pulse"></i> 测试结果
                    </button>
                </li>
            </ul>
            
            <div class="tab-content p-3 border border-top-0 rounded-bottom" id="resultsTabContent">
                <div class="tab-pane fade show active" id="requirements" role="tabpanel">
                    <div id="requirementsList" class="list-group"></div>
                    <div id="requirementsEmpty" class="text-center py-4 text-muted" style="display: none;">
                        <i class="bi bi-exclamation-circle"></i> 未找到需求信息
                    </div>
                </div>
                <div class="tab-pane fade" id="tests" role="tabpanel">
                    <div id="testsList" class="list-group"></div>
                    <div id="testsEmpty" class="text-center py-4 text-muted" style="display: none;">
                        <i class="bi bi-exclamation-circle"></i> 未找到测试结果
                    </div>
                </div>
            </div>
        </div>
        
        <div class="modal fade" id="detailModal" tabindex="-1" aria-hidden="true">
            <div class="modal-dialog modal-lg">
                <div class="modal-content">
                    <div class="modal-header bg-primary text-white">
                        <h5 class="modal-title" id="detailModalTitle">详细信息</h5>
                        <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
                    </div>
                    <div class="modal-body" id="detailModalBody">
                        <!-- 内容由JavaScript动态填充 -->
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        

        let currentProcessedFiles = null;
        document.addEventListener('DOMContentLoaded', function() {
            const uploadForm = document.getElementById('uploadForm');
            const processBtn = document.getElementById('processBtn');
            const loadingSection = document.getElementById('loadingSection');
            const resultsSection = document.getElementById('resultsSection');
            
            uploadForm.addEventListener('submit', async function(e) {
                e.preventDefault();
                
                const reqFile = document.getElementById('requirement').files[0];
                const testFile = document.getElementById('test').files[0];
                
                loadingSection.style.display = 'block';
                resultsSection.style.display = 'none';
                processBtn.disabled = true;
                processBtn.innerHTML = '<i class="bi bi-hourglass"></i> 处理中...';
                
                try {
                    // 上传文件
                    const formData = new FormData();
                    formData.append('requirement', reqFile);
                    formData.append('test', testFile);
                    
                    const uploadResponse = await fetch('/upload', {
                        method: 'POST',
                        body: formData
                    });
                    
                    const uploadData = await uploadResponse.json();
                    
                    if (!uploadResponse.ok || !uploadData.success) {
                        throw new Error(uploadData.error || '文件上传失败');
                    }
                    
                    // 处理文档
                    const processResponse = await fetch('/process', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify({
                            req_filename: uploadData.req_filename,
                            test_filename: uploadData.test_filename
                        })
                    });
                    
                    const processData = await processResponse.json();

                    function Path(path) {
                        return {
                            stem: path.replace(/\.[^/.]+$/, "").replace(/^req_\d+_/, "")
                        };
                    }

                    // 修改处理成功后的回调部分
                    if (processData.success) {
                        // 保存当前处理的文件名
                        currentProcessedFiles = {
                            req_filename: uploadData.req_filename,
                            test_filename: uploadData.test_filename,
                            doc_name: Path(reqFile.name).stem
                        };
                        
                        displayResults(processData.data);
                        resultsSection.style.display = 'block';
                    }
                    
                    if (!processResponse.ok || !processData.success) {
                        throw new Error(processData.error || '文档处理失败');
                    }
                    
                    // 显示结果
                    displayResults(processData.data);
                    resultsSection.style.display = 'block';
                    
                } catch (error) {
                    console.error('处理错误:', error);
                    alert('处理失败: ' + error.message);
                } finally {
                    loadingSection.style.display = 'none';
                    processBtn.disabled = false;
                    processBtn.innerHTML = '<i class="bi bi-gear"></i> 开始解析';
                }
            });
            
            function displayResults(results) {
                console.log('解析结果:', results);
                
                // 显示需求列表
                const reqList = document.getElementById('requirementsList');
                const reqEmpty = document.getElementById('requirementsEmpty');
                reqList.innerHTML = '';
                
                if (results.use_cases && results.use_cases.length > 0) {
                    reqEmpty.style.display = 'none';
                    results.use_cases.forEach((item) => {
                        const reqItem = document.createElement('div');
                        reqItem.className = 'list-group-item list-group-item-action';
                        reqItem.innerHTML = `
                            <div class="d-flex w-100 justify-content-between">
                                <h6 class="mb-1">${item.id ? item.id + ' - ' : ''}${item.name}</h6>
                                <small class="text-muted">${item.type}</small>
                            </div>
                            <p class="mb-1">${truncateText(item.description, 100)}</p>
                            <small class="text-muted">优先级: ${item.priority}</small>
                        `;
                        reqItem.onclick = () => showDetail(item, '需求');
                        reqList.appendChild(reqItem);
                    });
                } else {
                    reqEmpty.style.display = 'block';
                }
                
                // 显示测试结果
                const testsList = document.getElementById('testsList');
                const testsEmpty = document.getElementById('testsEmpty');
                testsList.innerHTML = '';
                
                if (results.test_results && results.test_results.length > 0) {
                    testsEmpty.style.display = 'none';
                    results.test_results.forEach((item) => {
                        const testItem = document.createElement('div');
                        
                        const statusClass = item.status === '通过' ? 'list-group-item-success' : 
                                         item.status === '失败' ? 'list-group-item-danger' : '';
                        const statusBadge = item.status ? `
                            <span class="badge bg-${
                                item.status === '通过' ? 'success' : 
                                item.status === '失败' ? 'danger' : 'warning'
                            }">${item.status}</span>
                        ` : '';
                        
                        testItem.className = `list-group-item list-group-item-action ${statusClass}`;
                        testItem.innerHTML = `
                            <div class="d-flex w-100 justify-content-between">
                                <h6 class="mb-1">${item.id ? item.id + ' - ' : ''}${item.name}</h6>
                                ${statusBadge}
                            </div>
                            <p class="mb-1"><strong>关联需求:</strong> ${item.requirement_id}</p>
                            ${item.objective ? `<p class="mb-1"><strong>测试目的:</strong> ${truncateText(item.objective, 80)}</p>` : ''}
                            ${item.method ? `<p class="mb-1"><strong>测试方法:</strong> ${truncateText(item.method, 80)}</p>` : ''}
                            <p class="mb-1"><strong>测试结果:</strong> ${truncateText(item.result, 100)}</p>
                        `;
                        testItem.onclick = () => showDetail(item, '测试');
                        testsList.appendChild(testItem);
                    });
                } else {
                    testsEmpty.style.display = 'block';
                }
            }
            
            function truncateText(text, maxLength) {
                if (!text) return '无内容';
                return text.length > maxLength ? text.substring(0, maxLength) + '...' : text;
            }
            
            function showDetail(item, type) {
                const modalTitle = document.getElementById('detailModalTitle');
                const modalBody = document.getElementById('detailModalBody');
                
                modalTitle.textContent = `${type}详情 - ${item.name || '未命名'}`;
                
                let html = '<dl class="row">';
                for (const [key, value] of Object.entries(item)) {
                    if (value === undefined || value === null || value === '') continue;
                    
                    let displayKey = key;
                    if (key === 'id') displayKey = 'ID';
                    else if (key === 'name') displayKey = '名称';
                    else if (key === 'type') displayKey = '类型';
                    else if (key === 'description') displayKey = '描述';
                    else if (key === 'priority') displayKey = '优先级';
                    else if (key === 'source') displayKey = '来源';
                    else if (key === 'requirement_id') displayKey = '关联需求ID';
                    else if (key === 'objective') displayKey = '测试目的';
                    else if (key === 'method') displayKey = '测试方法';
                    else if (key === 'result') displayKey = '测试结果';
                    else if (key === 'status') displayKey = '状态';
                    else if (key === 'evidence') displayKey = '证据';
                    else if (key === 'defect_id') displayKey = '缺陷ID';
                    
                    html += `
                        <dt class="col-sm-3">${displayKey}</dt>
                        <dd class="col-sm-9">${typeof value === 'string' ? value : JSON.stringify(value)}</dd>
                    `;
                }
                html += '</dl>';
                
                modalBody.innerHTML = html;
                
                const modal = new bootstrap.Modal(document.getElementById('detailModal'));
                modal.show();
            }
            
            

            // 修改导出按钮事件处理
            document.getElementById('downloadBtn').addEventListener('click', async function() {
                if (!currentProcessedFiles) {
                    alert('请先上传并处理文档');
                    return;
                }
                
                const downloadBtn = document.getElementById('downloadBtn');
                try {
                    downloadBtn.disabled = true;
                    downloadBtn.innerHTML = '<i class="bi bi-hourglass"></i> 准备下载...';
                    
                    // 请求下载报告
                    const response = await fetch('/download-report', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify({
                            req_filename: currentProcessedFiles.req_filename,
                            test_filename: currentProcessedFiles.test_filename
                        })
                    });
                    
                    if (!response.ok) {
                        const errorData = await response.json();
                        throw new Error(errorData.error || '下载失败');
                    }
                    
                    // 处理下载
                    const blob = await response.blob();
                    const url = window.URL.createObjectURL(blob);
                    const a = document.createElement('a');
                    a.href = url;
                    a.download = `${currentProcessedFiles.doc_name}_解析报告.txt`;
                    document.body.appendChild(a);
                    a.click();
                    document.body.removeChild(a);
                    window.URL.revokeObjectURL(url);
                    
                } catch (error) {
                    console.error('下载失败:', error);
                    alert(`下载失败: ${error.message}\n\n请尝试重新处理文档`);
                } finally {
                    downloadBtn.disabled = false;
                    downloadBtn.innerHTML = '<i class="bi bi-download"></i> 导出完整报告';
                }
            });

            
});
        localStorage.setItem('lastUploadData', JSON.stringify(uploadData));
    </script>
</body>
</html>